//子集
class Solution {
public:
    vector<int>tmp;
    vector<vector<int>>res;
    vector<vector<int>> subsets(vector<int>& nums) 
    {
        dfs(nums,0);
        return res;
    }
    //1  12  123 13 2 23 3
    void dfs(vector<int>&nums, int curi)
    {
        res.push_back(tmp);
        for(int i=curi;i<nums.size();i++)
        {
            tmp.push_back(nums[i]);
            dfs(nums,i+1);
            tmp.pop_back();
        }
    }

};
//子集II
class Solution {
public:
    vector<int>tmp;
    vector<vector<int>>res;

    vector<vector<int>> subsetsWithDup(vector<int>& nums) 
    {
        sort(nums.begin(),nums.end());
        vector<bool>used(nums.size(),false);
        dfs(nums,used,0);
        return res;
    }
    void dfs(vector<int>&nums,vector<bool>&used,int curi)
    {
        res.push_back(tmp);
        
        for(int i=curi;i<nums.size();i++)
        {
            if(i>0 && nums[i]==nums[i-1] && used[i-1]==false) continue;
            used[i]=true;
            tmp.push_back(nums[i]);
            dfs(nums,used,i+1);
            tmp.pop_back();
            used[i]=false;
        }
    }
};

//全排列
class Solution {
public:
    vector<int>tmp;
    vector<vector<int>>res;
    vector<bool>used;
    vector<vector<int>> permute(vector<int>& nums) 
    {
        used.resize(nums.size(),false);
        dfs(nums);
        return res;
    }
    void dfs(vector<int>&nums)
    {
        if(tmp.size()==nums.size())
        {
            res.push_back(tmp);
            return;
        }
        for(int i=0;i<nums.size();i++)
        {
            if(used[i]) continue;
            tmp.push_back(nums[i]);
            used[i]=true;
            dfs(nums);
            tmp.pop_back();
            used[i]=false;
        }
    }
};

//全排列II
class Solution {
public:
    vector<int>tmp;
    vector<vector<int>>res;
    vector<bool>used;
    vector<vector<int>> permuteUnique(vector<int>& nums) 
    {
        sort(nums.begin(),nums.end());
        used.resize(nums.size(),false);
        dfs(nums);
        return res;
    }
    void dfs(vector<int>&nums)
    {
        if(tmp.size()==nums.size()) 
        {
            res.push_back(tmp);
            return ;
        }

        for(int i=0;i<nums.size();i++)
        {
            if(i>0 && nums[i]==nums[i-1] && !used[i-1]) continue;
            if(used[i]) continue;
            used[i]=true;
            tmp.push_back(nums[i]);
            dfs(nums);
            used[i]=false;
            tmp.pop_back();
        }
    }
};